FREEAREA_TAGS = ('pre', 'xmp')


import re
import string

from django import template
from django.template.defaultfilters import stringfilter


register = template.Library()

@register.filter(name = 'smartbr')
def smartbr(value):
    _tags    = map(string.lower, FREEAREA_TAGS)
    pattern  = re.compile('(</?(?:%s)[^>]*>)' % '|'.join(_tags), re.IGNORECASE)
    freearea = False
    output   = ''
    
    for chunk in pattern.split(value):
        if True in map(lambda x : chunk[:1 + len(x)].lower() == '<%s' % x, _tags):
            freearea = True
        elif True in map(lambda x : chunk[:2 + len(x)].lower() == '</%s' % x, _tags):
            freearea = False

        if not freearea:
            chunk = re.sub('\r?\n', '<BR>\r\n', chunk)
            chunk = re.sub('<BR>\r?\n<BR>\r?\n', '<P>\r\n', chunk)

        output += chunk
    
    return output

